class Solution {
public:
    int pathSum(TreeNode* root, int sum) {
        if (root == nullptr) {
            return 0;
        }
        int count = pathSumHelper(root, sum);//从根节点出发去进行计算
        count += pathSum(root->left, sum);//从左子树寻找
        count += pathSum(root->right, sum);//去右子树寻找
        return count;//返回答案
    }
 
private:
    int pathSumHelper(TreeNode* node, int sum) {
        if (node == nullptr) {
            return 0;
        }
        //从该节点出发往下计算是否存在有效的路径长度
        int count = 0;
        if (node->val == sum) {
            count++;
        }
        count += pathSumHelper(node->left, sum - node->val);
        count += pathSumHelper(node->right, sum - node->val);
        return count;
    }
};